package net.chips.android.plugin.outmanage.kt

import android.content.Context
import android.util.Log
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import android.widget.TextView

/**
 * @author Administrator
 * Created by dab on 2021/7/21 10:31
 */


/***
 * 带延迟过滤的点击事件View扩展
 * @param delay Long 延迟时间，默认600毫秒
 * @param block: (T) -> Unit 函数
 * @return Unit
 */
@JvmOverloads
fun <T : View> T?.clickWithTrigger(time: Long = 600, block: (T) -> Unit) {
    if (this == null) {
        Log.e("TAG", "clickWithTrigger: null!!!!!!!!!!!" )
        return
    }

    triggerDelay = time
    setOnClickListener {
        if (clickEnable()) {
            block(it as T)
        }
    }
}

private var <T : View> T.triggerLastTime: Long
    get() = if (getTag(1123460103) != null) getTag(1123460103) as Long else -601
    set(value) {
        setTag(1123460103, value)
    }

private var <T : View> T.triggerDelay: Long
    get() = if (getTag(1123461123) != null) getTag(1123461123) as Long else 600
    set(value) {
        setTag(1123461123, value)
    }

private fun <T : View> T.clickEnable(): Boolean {
    var flag = false
    val currentClickTime = System.currentTimeMillis()
    if (currentClickTime - triggerLastTime >= triggerDelay) {
        flag = true
        triggerLastTime = currentClickTime
    }
    return flag
}

@JvmOverloads
fun View.openKeyBoard(hide: Boolean = false) {
    this.apply {
        isFocusable = !hide
        isFocusableInTouchMode = !hide
        requestFocus()
        if (!hide) {
            postDelayed({
                val imm =
                    context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
                imm.showSoftInput(this, 0)
            }, 200)
        } else {
            val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            imm.hideSoftInputFromWindow(this.windowToken, 0)
        }

    }
}

@JvmOverloads
fun TextView?.setTextDef(charSequence: CharSequence?, def: String = "暂无") {
    this?.text = charSequence ?: def

}